from subscriber import MQTTSubscriber
from apiRequest import save_token
from apiRequest import add_device
from apiRequest import handle_upload_command as up_cmd
import requests
import json
import time

# 配置参数
DEVICE_ID = "DUNQ3"  # 设备唯一ID
STATE = "active"
class DeviceSubscriber(MQTTSubscriber):
    def __init__(self, device_id=DEVICE_ID, broker="47.93.172.78", port=1883):
        self.device_id = device_id
        # 使用统一主题格式
        topic = f"device/{device_id}/commands"
        print(f"🔧 设备初始化完成 | 设备ID: {self.device_id}")
        super().__init__(broker=broker, port=port, keepalive=60, topic=topic, device_id=device_id)

    def _on_message(self, client, userdata, msg):
        """统一命令处理入口"""
        try:
            payload = json.loads(msg.payload.decode())
            print(f"📨 收到消息: {payload}")
            command = payload.get("command")
            data = payload.get("data", {})
            if command == "bind":
                self._handle_bind(data)
            elif command == "upload":
                self._handle_upload()
            elif command == "save_token":
                save_token(data["token"])
            else:
                print(f"未知命令: {command}")
        except json.JSONDecodeError:
            print("⚠️ 无法解析JSON消息")
        except Exception as e:
            print(f"消息处理错误: {str(e)}")

    def _handle_bind(self,data):
        """处理绑定命令"""
        if "token" not in data:
            print("⚠️ 绑定请求缺少token参数")
            return

        print("🔑 开始执行绑定流程...")
        token = data["token"]
        save_token(token)

        """模拟绑定设备到后端API"""
        print(f"🔄 正在绑定设备 (使用Token: {token[:6]}...)")
        add_device(STATE,DEVICE_ID)

    def _handle_upload(self):
        """处理图片上传命令"""
        print("📸 收到图片上传指令")
        # 调用上传模块
        up_cmd()


if __name__ =="__main__":
    binder = DeviceSubscriber()
